import { Image, Text } from "@tarojs/components";
import { chooseImage, showToast, getFileSystemManager } from "@tarojs/taro";
import { FC, ReactElement, useCallback } from "react";
import { FlexView } from "../../components/BUI";

interface IProps {
  imagePath: string | undefined;
  changeCodeImage: (image: string) => void;
}

const ImageSelect: FC<IProps> = ({
  imagePath = "",
  changeCodeImage,
}): ReactElement => {
  const handleImage = useCallback(() => {
    chooseImage({
      count: 1, // 默认9
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: ({ tempFiles: [{ path, size }] }) => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        if (size < 1024 * 1024 * 2) {
          changeCodeImage(path);
          const ArrayBuffer = getFileSystemManager().readFileSync(path);
          console.log(ArrayBuffer, size);
        } else {
          showToast({
            title: "图片大小不能大于2M",
            icon: "none",
            duration: 1000,
          });
        }
      },
    });
  }, [changeCodeImage]);

  return (
    <FlexView
      width='100%'
      height='70vh'
      bgc='#7270705c'
      justifyContent='center'
      alignItems='center'
    >
      <Image
        style={{
          width: "100%",
          height: "100%",
          position: "absolute",
        }}
        onClick={handleImage}
        src={imagePath}
      />
      <Text
        style={{
          color: "white",
          letterSpacing: "2px",
          textAlign: "center",
        }}
      >
        选择图片{`\n`}
        图片大小不能大于2M
      </Text>
    </FlexView>
  );
};

export default ImageSelect;
